//
//  BiSaleExecuteViewController.m
//  TrunkIndustryManageSystem
//
//  Created by WT_lyy on 15/4/22.
//  Copyright (c) 2015年 李璐西. All rights reserved.
//

#define BOTTOM_BUTTON_HEIGHT 40

#import "BiSaleExecuteCheckViewController.h"
#import "SaleExecuteCell.h"
#import "BiCustomerInfo.h"
#import "BiCustomerInfoViewController.h"
#import "BiGpsTrackViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "CLLocation+YCLocation.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchAPI.h>
@interface BiSaleExecuteCheckViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,CLLocationManagerDelegate,AMapSearchDelegate>{


    UITableView *_tableView;
    
    UILabel * _labSaleDhao;
    
    UILabel * _labGotime;
    
    UITextField * _textfLoct;
    
    NSMutableArray * _customerInfoList;
    
    UIButton * _btnStartExe;
    
    UIButton * _btnadd;
    UIButton * btngps;
    
    // location manager
    CLLocationManager* locationMgr;
    
    
    BOOL isFirstLocation;

    
    NSMutableArray * locArr;
    
    CLLocationCoordinate2D addCoornate;
    
}
@property (nonatomic, strong) AMapSearchAPI *search;
@end

@implementation BiSaleExecuteCheckViewController

@synthesize customerInfoList = _customerInfoList;

- (id)init
{
    self = [super init];
    if (self)
    {
        _customerInfoList = [[NSMutableArray alloc] init];
        
        isFirstLocation = NO;

        locArr = [[NSMutableArray alloc] init];
    }
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavBackBtn];
    
    [self setNavBarWithHidden:NO];
    
    [self setNavBarTitle:@"行销执行"];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, [self viewTop], MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT-[self viewTop]-BOTTOM_BUTTON_HEIGHT)];
    
    _tableView.delegate = self;
    
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
    _tableView.rowHeight = 125;
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tableView.tableHeaderView = [self _inittableheadView];
    
    _tableView.tableFooterView = [self _inittablefootView];
    
    UIButton * btnCheck = GET_BUTTON(CGRectMake(0, MAIN_SCREEN_HEIGHT-BOTTOM_BUTTON_HEIGHT, MAIN_SCREEN_WIDTH, BOTTOM_BUTTON_HEIGHT), 17, NO, [UIColor whiteColor]);
    
    [self.view addSubview:btnCheck];
    
    btnCheck.backgroundColor = UIColorFromRGB(BLUE_COLOR_VALUE);
    
    [btnCheck setTitle:@"审核" forState:UIControlStateNormal];
    
    [btnCheck addTarget:self action:@selector(btnCheckClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _btnadd.backgroundColor =[UIColor lightGrayColor];
     _btnadd.enabled = NO;
    if ([self.Centity.isExecuted intValue] == 1) {//若当前行销为正在执行的行销
        
        [_btnStartExe setTitle:@"结束行销" forState:UIControlStateNormal];
        _btnadd.enabled = YES;
        _btnadd.backgroundColor =[UIColor whiteColor];
    }else if([self.Centity.isExecuted intValue] == 2){//若当前行销为已结束但未审核
    
        _btnStartExe.hidden = YES;


    }
    
    if (self.Centity.startPlace.length == 0) {
        isFirstLocation = YES;
        [self openLocation];
    }else{
    
        _textfLoct.text = self.Centity.startPlace;
    }
    
    
    NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:self.Centity.e_id,@"id",[BiUserEntity sharedInstance].userid,@"userId", nil];
    
    [[BiNetEngine shareInstance] requestSaleGetCustomerList:self paraDict:paraDic];
}

- (void)openLocation{

    locationMgr = [[CLLocationManager alloc] init];
    locationMgr.delegate = self;
    locationMgr.desiredAccuracy = kCLLocationAccuracyBest;
    locationMgr.distanceFilter = FILTER_DISTANCE; //位置更新最小距离
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        [locationMgr requestAlwaysAuthorization];
        [locationMgr requestWhenInUseAuthorization];
    }
    
    if ([CLLocationManager locationServicesEnabled]) {
        // 启动位置更新
        // 开启位置更新需要与服务器进行轮询所以会比较耗电，在不需要时用stopUpdatingLocation方法关闭;
        [locationMgr startUpdatingLocation];
    }
    else {
        [self showMessage:@"请开启定位功能！"];
    }
}

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    [_tableView reloadData];
}


- (UIView *)_inittableheadView{

    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, 130)];
    
    UILabel * labDhao = GET_LABEL(CGRectMake(10, 10, 70, 16), 14, NO, [UIColor blackColor], NSTextAlignmentLeft);
    
    labDhao.text = @"行销单号:";
    
    [view addSubview:labDhao];
    
    _labSaleDhao = GET_LABEL(CGRectMake(80, 10, 200, 16), 14, NO, UIColorFromRGB(0x7d8793), NSTextAlignmentLeft);
    
    _labSaleDhao.text = self.Centity.systemNumber;
    
    [view addSubview:_labSaleDhao];
    
    UILabel * labCfa = GET_LABEL(CGRectMake(10, 32, 70, 16), 14, NO, [UIColor blackColor], NSTextAlignmentLeft);
    
    labCfa.text = @"出发时间:";
    
    [view addSubview:labCfa];
    
    
    _labGotime = GET_LABEL(CGRectMake(80, 32, 200, 16), 14, NO, UIColorFromRGB(0x7d8793), NSTextAlignmentLeft);
    _labGotime.text = [BiUtil stringFromFomate:[NSDate date] formate:@"yyyy-MM-dd hh:mm"];
    [view addSubview:_labGotime];
    
    UILabel * labloct = GET_LABEL(CGRectMake(10, 55, 70, 16), 14, NO, [UIColor blackColor], NSTextAlignmentLeft);
    
    labloct.text = @"起始位置:";
    
    [view addSubview:labloct];
    
    _textfLoct = [[UITextField alloc] initWithFrame:CGRectMake(80, 52, 230, 22)];
    
    [view addSubview:_textfLoct];
    
    _textfLoct.delegate = self;
    
    _textfLoct.layer.borderWidth = 0.5;
    
    _textfLoct.font = [UIFont systemFontOfSize:14];
    
    _textfLoct.layer.borderColor = UIColorFromRGB(BLUE_COLOR_VALUE).CGColor;
    
    _textfLoct.layer.cornerRadius = 4;
    
     _btnStartExe = GET_BUTTON(CGRectMake(240, 85, 70, 30), 14, NO,UIColorFromRGB(ORANGE_COLOR_VALUE));
    
    [view addSubview:_btnStartExe];
    
    _btnStartExe.layer.cornerRadius = 3;
    
    _btnStartExe.layer.borderColor = UIColorFromRGB(ORANGE_COLOR_VALUE).CGColor;
    
    _btnStartExe.layer.borderWidth = 1;
    
    [_btnStartExe setTitle:@"开始行销" forState:UIControlStateNormal];
    
    _btnStartExe.tag = 101;
    
    [_btnStartExe addTarget:self action:@selector(btnStartEndExeClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
   btngps = GET_BUTTON(CGRectMake(130, 85, 90, 30), 14, NO,UIColorFromRGB(ORANGE_COLOR_VALUE));
    
    [view addSubview:btngps];
    
    btngps.layer.cornerRadius = 3;
    
    btngps.layer.borderColor = UIColorFromRGB(ORANGE_COLOR_VALUE).CGColor;
    
    btngps.layer.borderWidth = 1;
    
    [btngps setTitle:@"行销轨迹" forState:UIControlStateNormal];
    
    btngps.tag = 102;
    
    [btngps setImage:LOAD_IMAGE_WITH_CACHE(@"CarSale/map") forState:UIControlStateNormal];
    [btngps setImageEdgeInsets:UIEdgeInsetsMake(6, 5, 6, 65)];
    [btngps setTitleEdgeInsets:UIEdgeInsetsMake(0, -13, 0, 0)];
    [btngps addTarget:self action:@selector(btngpsClick:) forControlEvents:UIControlEventTouchUpInside];
    
    if ([self.Centity.isExecuted integerValue] == 2) {
        btngps.frame = _btnStartExe.frame;
        
        _btnadd.hidden = YES;
    }
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 125, MAIN_SCREEN_WIDTH, 1)];
    
    [view addSubview:lineView];
    
    lineView.backgroundColor = UIColorFromRGB(0xe0e0e0);
    
    return view;
}


- (UIView *)_inittablefootView{
    
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, 150)];

    _btnadd = GET_BUTTON(CGRectMake(220, 10, 90, 30), 14, NO, UIColorFromRGB(ORANGE_COLOR_VALUE));
    
    [view addSubview:_btnadd];
    
    _btnadd.layer.cornerRadius = 3;
    
    _btnadd.layer.borderColor = UIColorFromRGB(ORANGE_COLOR_VALUE).CGColor;
    
    _btnadd.layer.borderWidth = 1;
    
    [_btnadd setTitle:@"添加客户信息" forState:UIControlStateNormal];
    
    [_btnadd addTarget:self action:@selector(btnAddClick:) forControlEvents:UIControlEventTouchUpInside];

    
    UILabel * labrsn = GET_LABEL(CGRectMake(10, 40, 300, 18), 14, NO, [UIColor blackColor], NSTextAlignmentLeft);
    
    [view addSubview:labrsn];
    
    labrsn.text = @"驳回原因:";
    
    UITextView * textvRsn = [[UITextView alloc] initWithFrame:CGRectMake(10, 62, 300, 75)];
    
    textvRsn.editable = NO;
    
    [view addSubview:textvRsn];
    
    textvRsn.layer.borderColor = UIColorFromRGB(0xe0e0e0).CGColor;
    
    textvRsn.layer.borderWidth = 0.5;
    
    textvRsn.text = self.Centity.xingxiaoRejectReason;
    
    return view;
}

#pragma -mark  Button Action
- (void)btnStartEndExeClick:(UIButton *)sender{
    if (_btnStartExe.currentTitle.hash == @"结束行销".hash) {
        //停止定位
        if (locationMgr) {
            
            [locationMgr stopUpdatingLocation];
            
            locationMgr.delegate = nil;
            
            locationMgr = nil;
            
        }
        
        NSMutableArray * gpsArr = [NSMutableArray array];
        
        NSDictionary * firDic = nil;
        NSString * sqlStr = [NSString stringWithFormat:@"select * from table_track where systemNum=%@ order by creatdate asc",self.Centity.e_id];
        
        [locArr removeAllObjects];
        [locArr addObjectsFromArray:[[DBManager sharedInstance] querryTable:sqlStr]];
        if (locArr.count > 0) {
            
            firDic  = [locArr firstObject];
        }
        
        for (int i = 0; i<locArr.count; i++) {
            
            NSDictionary * tempDic = locArr[i];
            
            double totalDis = 0;
            if (0 == i) {
                totalDis = 0;
            }
            
            if (i == 1) {
                 totalDis = [self computeTotalDis:firDic end:tempDic];
            }else{
                
                NSDictionary *  laDic = [gpsArr lastObject];
            
                totalDis = [self computeTotalDis:locArr[i-1] end:tempDic] + [laDic[@"totalDistance"] doubleValue];
            }
            
            
            double totalTime = [self computeTotalTime:firDic end:tempDic];

            NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:self.Centity.e_id,@"sellId",
                                      tempDic[@"latitude"],@"latitude",
                                      tempDic[@"longitude"],@"longitude",
                                      [NSNumber numberWithDouble:totalDis],@"totalDistance",
                                      [NSNumber numberWithDouble:totalTime],@"totalTime",nil];
            
            [gpsArr addObject:paraDic];
            
        }
        
        NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:self.Centity.e_id,@"sellId",
                                  [BiUtil stringFromFomate:[NSDate date] formate:TIME_FOMTTER],@"trueEndTime",
                                  @"",@"trueTotalTime",
                                  @"",@"trueTotalDistance",
                                  gpsArr,@"gpsInfo", nil];
        
        [[BiNetEngine shareInstance] requestSaleEnd:self paraDic:paraDic];
        
        [self asyshowHUDView:WAITING CurrentView:self];
        
    }else if (_btnStartExe.currentTitle.hash == @"开始行销".hash){
        
        NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:self.Centity.e_id,@"id",
                                  _labGotime.text,@"trueStartTime",
                                  _textfLoct.text,@"startPlace",nil];
        
        [[BiNetEngine shareInstance] requestSaleStart:self paraDict:paraDic];
        
        [self asyshowHUDView:WAITING CurrentView:self];
    }
}



//计算gps点的总时间
- (double )computeTotalDis:(NSDictionary *)fronDic end:(NSDictionary *)toDic{

    //此处断点提示 距离计算 修改为火星坐标
    CLLocation *form = [[CLLocation alloc] initWithLatitude:[fronDic[@"latitude"] doubleValue]  longitude:[fronDic[@"longitude"] doubleValue]];
    
    CLLocation *to = [[CLLocation alloc] initWithLatitude:[toDic[@"latitude"] doubleValue]  longitude:[toDic[@"longitude"] doubleValue]];
    
    return  [form distanceFromLocation:to];
    
    
}

//计算gps点的总距离
- (double)computeTotalTime:(NSDictionary *)fronDic end:(NSDictionary *)toDic{

    NSDate * startDate = [BiUtil dateFromFomate:fronDic[@"creatdate"] formate:@"yyyy-MM-dd hh:mm:ss"];
    
    NSDate * endDate = [BiUtil dateFromFomate:toDic[@"creatdate"] formate:@"yyyy-MM-dd hh:mm:ss"];
    
    return  [endDate timeIntervalSinceDate:startDate];
}


- (void)btnCheckClick:(UIButton *)sender{


    NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:self.Centity.e_id,@"id",
                              [BiUserEntity sharedInstance].userid,@"xingxiaoApproverId",
                              @"1",@"status",
                              nil];
    
    [[BiNetEngine shareInstance] requestSaleApplyCheck:self paraDict:paraDic];
    
    [self asyshowHUDView:WAITING CurrentView:self];
}

- (void)btnAddClick:(UIButton *)sender{
    
    BiCustomerInfoViewController * cusVctrl = [[BiCustomerInfoViewController alloc] init];
    
    cusVctrl.Centity = self.Centity;
    
    cusVctrl.phoneJudgeArr = _customerInfoList;
    
    [self.navigationController pushViewController:cusVctrl animated:YES];
    
}


- (void)btngpsClick:(UIButton *)sender{
    
    BiGpsTrackViewController * gpsVctrl = [[BiGpsTrackViewController alloc] init];
    
    gpsVctrl.e_id = self.Centity.e_id;
    
    if (_customerInfoList.count>0) {
        
        gpsVctrl.cusTomerArr = _customerInfoList;
    }
    
    gpsVctrl.isExecuted = [self.Centity.isExecuted integerValue];
 
    gpsVctrl.polylineCoord = addCoornate;
    
    [self.navigationController pushViewController:gpsVctrl animated:YES];
}


#pragma -mark  UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}


#pragma -mark UitabeViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    BiCustomerInfoViewController * cusVctrl = [[BiCustomerInfoViewController alloc] init];
    
    cusVctrl.Centity = self.Centity;
    
    cusVctrl.cusEntity = _customerInfoList[indexPath.row];
    
    [self.navigationController pushViewController:cusVctrl animated:YES];
}

#pragma -mark UitabeViewDatasource

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (_customerInfoList) {
        
        return _customerInfoList.count;
    }
    
    return 0;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * myIndentifier = @"SaleExecuteCell";
    
    SaleExecuteCell * cell = (SaleExecuteCell *)[tableView dequeueReusableCellWithIdentifier:myIndentifier];
    
    if (!cell)
    {
        
        NSArray * arr = [[NSBundle mainBundle] loadNibNamed:@"SaleExecuteCell" owner:self options:nil];
        cell = [arr firstObject];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    BiCustomerInfo * info = _customerInfoList[indexPath.row];
    
    cell.labaddress.text = info.collectAddress;
    
    cell.labName.text = info.customerName;
    
    cell.labTEl.text = info.customerPhone;
    
    cell.labTime.text = info.collectTime;
    
    cell.headImv.tag = indexPath.row;
    
    [cell setAddheitht:info.collectAddress];
    
    cell.headImv.image = LOAD_IMAGE_WITHOUT_CACHE(@"CarSale/default.png");
    
    if(info.imageCust){
    
        cell.headImv.image = info.imageCust;
    }else if (info.imageCustCar){
        cell.headImv.image = info.imageCustCar;
    }else if (info.imageCustEat){
        cell.headImv.image = info.imageCustEat;
    }else if (info.visitorCustomerPhoto.length != 0) {
        
        [self reloadImage:info.visitorCustomerPhoto withIm:cell.headImv info:info];
    }else if (info.customerCarphoto.length != 0){
        [self reloadImage:info.customerCarphoto withIm:cell.headImv info:info];
    }else if (info.restaurantPhoto.length != 0){
        [self reloadImage:info.restaurantPhoto withIm:cell.headImv info:info];
    }
    
    return cell;
}


-(void)reloadImage:(NSString *)url withIm:(UIImageView *)imview info:(BiCustomerInfo *)info{
    if (!url||[url isEqual:[NSNull null]] || [url isEqualToString:@"<null>"] || url.length==0) {
        [imview setImage:nil];
        return;
    }
    NSString *url_ =[NSString stringWithFormat:@"%@%@",SERVICE_URL_FORMAL,url];
    
    NSString *localPath = [NSString stringWithFormat:@"%@/%@",[BiUtil tempImageFilePath],[url lastPathComponent]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
        [imview setImage:[UIImage imageWithContentsOfFile:localPath]];
    }else {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url_]];
        [request setHTTPMethod:@"GET"];
        NSOperationQueue *queue = [NSOperationQueue mainQueue];
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:queue
                               completionHandler:^(NSURLResponse *response,
                                                   NSData *data,
                                                   NSError *error){
                                   if (data) {
                                           dispatch_async(dispatch_get_main_queue(), ^{
                                               UIImage *downLoadImage = [UIImage imageWithData:data];
                                               if (downLoadImage.size.width >110 ) {
                                                   downLoadImage  =[BiUtil scaleToSize:downLoadImage size:CGSizeMake(110,  downLoadImage.size.height*110/downLoadImage.size.width)];
                                               }
                                               [imview setImage:downLoadImage];
                                               [imview setNeedsDisplay];
                                               [imview setNeedsLayout];
                                               if (0 == imview.tag) {
                                                   info.imageCust = downLoadImage;
                                               }else if (1 == imview.tag){
                                                   info.imageCustCar = downLoadImage;
                                               }else if (1 == imview.tag){
                                                   info.imageCustEat = downLoadImage;
                                               }
                                               dispatch_queue_t bgque = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                                               dispatch_async(bgque, ^{[data writeToFile:localPath atomically:YES];});
                                               
                                           });
                                       }
                                   
                               }];
    }
}


#pragma mark - AMapSearchDelegate

/* 逆地理编码回调. */

-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{

    
    //NSLog(@"%@",response);
    
    NSString * addrestr =  response.regeocode.formattedAddress;
    
    addrestr = [addrestr substringFromIndex:3];
    
    _textfLoct.text = addrestr;

    
}


#pragma mark - CLLocationManagerDelegate
 //地理位置发生改变时触发
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    
    if (isFirstLocation) {
        
        self.search = [[AMapSearchAPI alloc] initWithSearchKey:[MAMapServices sharedServices].apiKey Delegate:self];
        
        addCoornate = [newLocation locationMarsFromEarth].coordinate;

        [self searchReGeocodeWithCoordinate:addCoornate];
        
        [locationMgr stopUpdatingLocation];
        
        locationMgr = nil;
        
        locationMgr.delegate = nil;
        
        isFirstLocation = NO;
        
        return;
    }

    newLocation = [newLocation locationMarsFromEarth];
    
    NSDictionary *posiDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                              self.Centity.e_id,@"systemNum",
                              [NSString stringWithFormat:@"%f",newLocation.coordinate.latitude],@"latitude",
                              [NSString stringWithFormat:@"%f",newLocation.coordinate.longitude], @"longitude",
                              [BiUtil stringFromFomate:[NSDate date] formate:@"yyyy-MM-dd hh:mm:ss"], @"creatdate", nil];
    
    if (![[DBManager sharedInstance] insertDataDictionary:posiDict toTable:@"table_track"])
    {
        NSLog(@"写入数据库失败！");
    }else{
        NSLog(@"写入数据库成功！");
    }
    
    
    if (locArr.count == 0) {
        NSString * sqlStr = [NSString stringWithFormat:@"select * from table_track where systemNum=%@ order by creatdate asc",self.Centity.e_id];
        
        [locArr removeAllObjects];
        [locArr addObjectsFromArray:[[DBManager sharedInstance] querryTable:sqlStr]];
    }else{
    
        [locArr addObject:posiDict];
    }

    if (locArr.count >2) {
        NSInteger kmetr = (locArr.count-2)*FILTER_DISTANCE;
        
        [self showMessage:[NSString stringWithFormat:@"总距离：%d米",(int)kmetr]];
    }
    
}


// 定位失误时触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error);
}


- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    
    regeo.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    regeo.requireExtension = YES;
    
    [self.search AMapReGoecodeSearch:regeo];
    
}


#pragma -mark Net Delegate
- (void)onNetEngineResponse:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    
    [self removeHUDView:self];

    NSDictionary * entity_ = (NSDictionary *)entity;
    
    [self showMessage:entity_[@"result_info"]];
    
    if ([entity_[@"response_status"] integerValue] != 200) {
        
        return;
        
    }
    
    switch (tag) {
        case NET_GET_XINGXIAO_START_SALE:
        {
            [self operateForStartSale];
            
        }
            break;

        case NET_GET_XINGXIAO_GETCUSTOMER_LIST:
        {
            [_customerInfoList removeAllObjects];
        
            NSArray * arr = entity_[@"data"];
            
            [_customerInfoList addObjectsFromArray:arr];
            
            [_tableView reloadData];
        }
            break;
        case NET_GET_XINGXIAO_SALEAPPLY_CHECK:
        {
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }
            break;
        case NET_GET_XINGXIAO_END_SALE:
        {
            
            btngps.frame = _btnStartExe.frame;
            
            _btnStartExe.hidden = YES;
            
            _btnadd.hidden = YES;
 
        }
            break;
        default:
            break;
    }
    

}
- (void)onNetEngineResponseFail:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    [self removeHUDView:self];
    
}


- (void)operateForStartSale{

    _btnadd.backgroundColor = [UIColor whiteColor];
    _btnadd.enabled = YES;
    [_btnStartExe setTitle:@"结束行销" forState:UIControlStateNormal];
    
    if (!locationMgr) {
        locationMgr = [[CLLocationManager alloc] init];
    }
    locationMgr.delegate = self;
    locationMgr.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    locationMgr.distanceFilter = FILTER_DISTANCE; //位置更新最小距离
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        [locationMgr requestAlwaysAuthorization];
        [locationMgr requestWhenInUseAuthorization];
    }
    
    if ([CLLocationManager locationServicesEnabled]) {
        // 启动位置更新
        // 开启位置更新需要与服务器进行轮询所以会比较耗电，在不需要时用stopUpdatingLocation方法关闭;
        [locationMgr startUpdatingLocation];
    }
    else {
        [self showMessage:@"请开启定位功能！"];
        
        
    }
    
    if([BiUtil isBlankString:_textfLoct.text]){
        
        [self showMessage:@"请定位起始地址！"];
        
        return;
    }
}

@end
